package com.pc_project.service.impl;

import com.pc_project.domain.Audit;
import com.pc_project.domain.authenticate.AuditAuthenticator;
import com.pc_project.domain.VO.AuditLogin;
import com.pc_project.domain.VO.JsonVO;
import com.pc_project.mapper.AuditDao;
import com.pc_project.service.AuditService;
import com.pc_project.utils.RedisCache;
import com.pc_project.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

//审核者service实现类
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    private AuditLogin auditLogin;

    @Autowired
    private AuditDao auditDao;


    //    利用注入到容器的AuthenticationManager来进行authenticate方法认证
    @Autowired
    private AuthenticationManager authenticationManager;

// redis帮助类
    @Autowired
    private RedisCache redisCache;

//    登录方法实现
    @Override
    public JsonVO login(String ausername, String apassword) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(ausername, apassword);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        如果认证不成功那么对象就会为空。
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
//        认证成功我们就生成token
        AuditAuthenticator authenticator= (AuditAuthenticator) authenticate.getPrincipal();
        Audit audit=authenticator.getAudit();
        String aid= audit.getAid().toString();
        String jwt= TokenUtils.createToken(aid);
//        将完整信息存入redis
        redisCache.setCacheObject("login:" + aid, authenticator);
//        存入redis后将信息返回给前端
        HashMap<String, Object> map = new HashMap<>();
//        将信息转化为vo信息
        auditLogin.setANickname(audit.getANickname());
        auditLogin.setAUsername(audit.getAUsername());
        auditLogin.setRole(audit.getRole());
        auditLogin.setToken(jwt);
        map.put("audit",auditLogin);
//      todo:  返还给前端后我们还需要做一个操作就是将最后修改时间修改。
        audit.setLastUpdate(new Date());
        auditDao.updateByPrimaryKey(audit);
        return JsonVO.success(map);
    }

//    登出方法
    @Override
    public JsonVO logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuditAuthenticator  authenticator = (AuditAuthenticator) authentication.getPrincipal();
        Integer userid = authenticator.getAudit().getAid();
        redisCache.deleteObject("login:" + userid);
        return JsonVO.success(null);
    }

}
